import { defineStore } from 'pinia'
import { ref } from 'vue'
import authService from '@/services/authService'
import { getToken, setToken, removeToken } from '@/utils/auth'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(getToken())
  const userInfo = ref(null)
  const isLoggedIn = ref(!!token.value)

  // 登录
  const login = async (loginForm) => {
    try {
      const response = await authService.login(loginForm)
      const { token: newToken, userInfo: newUserInfo } = response.data
      
      // 保存token
      token.value = newToken
      setToken(newToken)
      
      // 保存用户信息
      userInfo.value = newUserInfo
      isLoggedIn.value = true
      
      return response
    } catch (error) {
      throw error
    }
  }

  // 退出登录
  const logout = async () => {
    try {
      await authService.logout()
    } catch (error) {
      console.error('退出登录失败:', error)
    } finally {
      // 清除本地数据
      token.value = null
      userInfo.value = null
      isLoggedIn.value = false
      removeToken()
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await authService.getUserInfo()
      userInfo.value = response.data
      return response
    } catch (error) {
      // 如果获取用户信息失败，可能是token过期
      await logout()
      throw error
    }
  }

  // 刷新token
  const refreshToken = async () => {
    try {
      const response = await authService.refreshToken()
      const { token: newToken } = response.data
      
      token.value = newToken
      setToken(newToken)
      
      return response
    } catch (error) {
      // 刷新失败，退出登录
      await logout()
      throw error
    }
  }

  // 检查登录状态
  const checkAuth = () => {
    const currentToken = getToken()
    if (currentToken) {
      token.value = currentToken
      isLoggedIn.value = true
      // 获取用户信息
      getUserInfo().catch(() => {
        // 获取失败，可能token过期
        logout()
      })
    } else {
      isLoggedIn.value = false
    }
  }

  return {
    // 状态
    token,
    userInfo,
    isLoggedIn,
    
    // 方法
    login,
    logout,
    getUserInfo,
    refreshToken,
    checkAuth
  }
})
